package com.sskj.xgja.api;

import com.sskj.base.Constant;
import com.sskj.xgja.MyApplication;

import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class RetrofitFactory {
    public static Retrofit retrofit;

    private RetrofitFactory() {
        retrofit = new Retrofit.Builder()
                .baseUrl(Constant.SERVER_ADDRESS)
                .addConverterFactory(GsonConvertFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(initClient())
                .build();
    }

    private OkHttpClient initClient() {
        return new OkHttpClient.Builder()
                .addInterceptor(initHeaderInterceptor())
                .addInterceptor(initLogInterceptor())
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    private Interceptor initLogInterceptor() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return interceptor;

    }

    private Interceptor initHeaderInterceptor() {
        Interceptor headerInterceptor = chain -> {
            Request request = chain.request();
            HttpUrl.Builder commonParamsUrlBuilder = request.url()
                    .newBuilder()
                    .scheme(request.url().scheme())
                    .host(request.url().host())
                    .addQueryParameter("systemType", "ANDROID")
                    .addQueryParameter("account", MyApplication.getAccount())
                    .addQueryParameter("token", MyApplication.getToken());
            request = request.newBuilder()
                    .addHeader("systemType", "ANDROID")
                    .addHeader("account", MyApplication.getAccount())
                    .addHeader("token", MyApplication.getToken())
                    .method(request.method(), request.body())
                    .url(commonParamsUrlBuilder.build())
                    .build();

            return chain.proceed(request);
        };
        return headerInterceptor;
    }


    public static RetrofitFactory instance;


    public static <T> T create(Class<T> service) {
        if (instance == null) {
            instance = new RetrofitFactory();
        }
        return retrofit.create(service);
    }
}
